package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.aduser.dtos.AdUserDto;
import com.heima.model.aduser.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 管理员登录
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //校验参数
        if (adUserDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询用户是否存在
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }
        //获得盐
        String salt = adUser.getSalt();
        //输入的密码
        String pd = adUserDto.getPassword();
        String password = DigestUtils.md5DigestAsHex((pd + salt).getBytes());
        if (!password.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误!");
        }
        //返回数据
        Map<String,Object> map=new HashMap<>();
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        map.put("user",adUser);

        return ResponseResult.okResult(map);
    }
}
